package com.etc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.config.AlipayConfig;
import com.etc.entity.Items;
import com.etc.entity.Orders;
import com.etc.entity.ShopcObj;
import com.etc.entity.User;
import com.etc.zmall.service.OrdersService;
import com.etc.zmall.service.impl.OrdersServiceImpl;

/**
 * Servlet implementation class OrderServlet
 */
@WebServlet("/os.do")
public class OrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	OrdersService ordersService = new OrdersServiceImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("createOrder".equals(op)) {
			// 后台订单先生成:
			doCreateOrder(request, response);
			// 调用
			// doAlipay(request, response);
		} else if ("upOrderState".equals(op)) {
			doUpdateOrderState(request, response);
		}
	}

	/**
	 * 
	
	* <p>Title: doUpdateOrderState</p>
	
	* <p>Description: 支付结束后更新订单的状态 </p>
	
	* @param request
	* @param response
	* @throws ServletException
	* @throws IOException
	 */
	protected void doUpdateOrderState(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String orderid = request.getSession().getAttribute("orderid") + "";
		boolean flag = ordersService.upOrdersState(1, orderid);
		//判断(订单)
		response.sendRedirect("efront/Cart.jsp");

	}

	protected void doCreateOrder(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 存储在session中
		HttpSession session = request.getSession();

		List<ShopcObj> list = (List<ShopcObj>) session.getAttribute("list");
		// 登录信息在session
		User user = (User) session.getAttribute("user");
		
		System.out.println("userid : " + user.getUserid());
		

		Date date = new Date();
		// 可以用 SimpleDateFormat
		SimpleDateFormat simple = new SimpleDateFormat("yyyyMMddHHmmss");
		System.out.println("orderid: " + simple.format(date) + new Random().nextInt(1000));
		String orderid = simple.format(date) + new Random().nextInt(1000);

		// foreach
		System.out.println("os.do ....");
		list.forEach(s -> System.out.println(s.getGoodsid() + "," + s.getGoodsname() + "," + s.getTotal()));
		int ordersum = 0;

		List<Items> itemsList = new ArrayList<Items>();
		Items item = null;
		for (ShopcObj shopcObj : list) {
			ordersum += shopcObj.getGoodscount();
			//
			int count = shopcObj.getGoodscount();
			int goodsid = shopcObj.getGoodsid();
			int shopid = shopcObj.getShopid();
			int shopcid = shopcObj.getShopcid();
			double cost = shopcObj.getTotal();
			// new Items(count, goodsid, orderid, cost, userid, shopid, shopcid)
			item = new Items(count, goodsid, orderid, cost, user.getUserid(), shopid, shopcid);
			//添加到订单项集合.
			itemsList.add(item);

		}

		System.out.println("ordersum: " + ordersum);

		double ztotal = (double) session.getAttribute("ztotal");
		System.out.println("ztotal : " + ztotal);

		// 需要构造一个Orders对象给Service调用
		Orders orders = new Orders(orderid, ordersum, user.getUserid(), ztotal);
		// 再赋值LIist<Items>
		orders.setItems(itemsList);

		// 调用service的方法
		boolean flag = ordersService.addOrder(orders);

		System.out.println("flag : " + flag);

		// order存入session
		request.getSession().setAttribute("orderid", orderid);

		// 根据判断来决定下一步的支付： 测试
		doAlipay(request, response);

	}

	protected void doAlipay(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 后台订单先生成:

		// 数据库订单的表结构：

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		// 获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
				AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key,
				AlipayConfig.sign_type);

		// 设置请求参数
		AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		alipayRequest.setReturnUrl(AlipayConfig.return_url);
		alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

		// 商户订单号，商户网站订单系统中唯一订单号，必填
		String out_trade_no = new String(System.currentTimeMillis() + "");

		double ztotal = (double) request.getSession().getAttribute("ztotal");
		System.out.println("ztotal : " + ztotal);

		// 付款金额，必填
		String total_amount = ztotal + "";
		// 订单名称，必填
		String subject = new String("zmall-VIP");
		// 商品描述，可空
		String body = new String("goods");

		alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\"" + total_amount
				+ "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
				+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

		// 若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
		// alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
		// + "\"total_amount\":\""+ total_amount +"\","
		// + "\"subject\":\""+ subject +"\","
		// + "\"body\":\""+ body +"\","
		// + "\"timeout_express\":\"10m\","
		// + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
		// 请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

		// 请求
		try {
			String result = alipayClient.pageExecute(alipayRequest).getBody();

			// **必须要有的
			out.print(result);
			System.out.println("result :" + result);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//订单状态修改.
		

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
